<template>
  <div ref="myDiv" class="dialogue_area" :style="{ height:'100%',width:(this.pageWidth-35)+'px' }">
    <el-row :gutter="20" style="margin: 16px 10px 0 10px;">
      <div class="record_section"  ref="dialogContainer"  :style="listdata.flag ?{ height:'88.5vh'} : {}">
        <el-row :gutter="20">
          <div class="dialogue_component">
            <div  :key="index" v-for="(item, index) in recordList">
              <plain-text-reply v-if="item.flag == 'NewConversation'" :itemData="item"/> <!-- hi  -->
              <customer-issues  v-if="item.flag == 'AssistantQuotation'" :itemData="item"/> <!-- 用户问题  -->
              <scheduling-processing v-if="item.flag == 'AnswerRendering'" :itemData="item" :childType="item.data.data.type" :childId="item.data.data.childId" :propsContent="propsContent" :dialogueDetailData="dialogueDetailData"/> <!-- 回答渲染 -->
              <error v-if="item.flag == 'error'" :itemData="item"/> <!-- error -->
              <date-component v-if="item.flag == 'dateAndTime'" :itemData="item"/>
            </div>
            <analyzing v-if="NewConversation" /> <!-- 解析中 -->
          </div>
        </el-row>
      </div>
    </el-row>
    <el-row :gutter="40" style="margin: 60px 0 40px 10px;">
      <div v-if="!listdata.flag" class="input_border" @mouseenter="handleMouseEnter"  @mouseleave="handleMouseLeave">
        <div class="input_box" :style="{ height: input_box_height + 'px' }" >
          <el-col :span="22">
            <!-- <div class="rich_textarea" ref="rich_textarea" contenteditable="true" v-html="formattedContent" :key="formattedContent" @input="updateContent" @click="clearContent" @paste="onPaste">
            </div> -->
            <div ref="rich_textarea">
            <el-input class="centered-input" type="textarea" :autosize="true" :rows="2" placeholder="请输入你的交易要求" v-model="formattedContent"  @keyup.enter.native="keyDown"> </el-input>
            </div>
          </el-col>
          <el-col :span="2" :offset="22" class="send_ntype">
            <div :class="this.send_button"  @click="sendQuestions">

            </div>
          </el-col>
        </div>
      </div>
      <!-- </div> -->
    </el-row>
  </div>
</template>

<script>
import plainTextReply from '@/layout/dialogue_component/plainTextReply.vue'
import customerIssues from '@/layout/dialogue_component/customerIssues.vue'
import analyzing from '@/layout/dialogue_component/analyzing.vue'
import schedulingProcessing from '@/layout/dialogue_component/schedulingProcessing.vue'
import error from '@/layout/dialogue_component/error.vue'
import dateComponent from '@/layout/dialogue_component/dateComponent.vue'
import {getAnswersByQuestion, getConversationDetails, getProcessingProcess, dialoguequery,adddialogue  } from '@/api/baiduapi.js'
export default {
  components: {
    plainTextReply,
    customerIssues,
    analyzing,
    schedulingProcessing,
    error,
    dateComponent
  },
  props:{
    listdata: {
      type: Object,
      default: function() {
        return {}
      }
    },
    pageWidth: {
      type: Number,
      default: ''
    }
  },
  data() {
    return {
      send_button:'send_button1',
      recordList: [{
        flag: 'NewConversation',
      },
      ],
      content: '请输入你的交易要求', // 存储纯文本内容
      formattedContent: '', // 存储格式化后的HTML内容
      divHeight: 0,
      observer: null,
      firstHeight: '',
      input_box_height:'',
      isEnter: '',
      NewConversation : false,
      propsContent:'',
      id:'',
      dialogueDetailId:'',
      dialogueDetailData:{},
      childId:'',
      message:'',
      count:0,
      bordflag : false,
    };
  },
  watch: {
    recordList: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  },
  beforeDestroy() {  
    // 在组件销毁前移除事件监听器  
    // window.removeEventListener("keyup", this.keyDown);  
  },  
  mounted() {
    // window.removeEventListener("keyup", this.sendQuestions);
    // window.addEventListener("keyup", this.keyDown); //监听回车事件
    // this.formattedContent = this.content; // 初始化formattedContent
    if(this.listdata.type==='1'){
      console.log('this.listdata',this.listdata)
      this.updateDivHeight()
      console.log('进聊天框')
      this.bordflag = false
      this.observeDivHeight();
      if (this.listdata.id > 0 && this.listdata.id !== '+' && this.id !== this.listdata.id) {
        console.log('ssss')
        this.getConversationDetails()
        // this.getActivitiesData(this.dialogueDetailId)
      }
      if(this.listdata.text){
        this.formattedContent = this.listdata.text
        this.sendQuestions()
      }
    }else {
      this.listdata.flag = "1"
      console.log('this.listdata',this.listdata)
      this.observeDivHeight();
      console.log('未进聊天框')
      this.bordflag = true
      // this.input_box_height = 60
      // console.log('this.input_box_height',this.input_box_height)
    }
    // this.observeDivWidth();
  },
  methods: {
    handleMouseEnter() {  
      // console.log('鼠标悬浮了！');  
      // 在这里执行你需要的操作（鼠标进入时）  
      this.send_button='send_button'
    },  
    handleMouseLeave() {  
      // console.log('鼠标离开了！');  
      // 在这里执行你需要的操作（鼠标离开时）  
      this.send_button='send_button1'
    },  
    getConversationDetails(){
      console.log('对话框请求进来了')
      this.id = this.listdata.id
      getConversationDetails(1, 100, this.id).then(res => {
        var data = res.data.list
        console.log('res==>', res)
        this.recordList = []
        if (data.length > 0) {
          for (let i = data.length - 1; i >= 0; i--) {
            this.recordList.push({
              flag: 'dateAndTime',
              content: data[i].createTime
            })
            this.recordList.push({
              flag: 'AssistantQuotation',
              content: data[i].question
            })
            if (data[i].answer.length === 0) {
              this.recordList.push({
                flag: 'AnswerRendering',
                // data:{list: data[i].noAnswer, childId: data[i].id}
                data: {
                  data:{list: data[i].noAnswer, childId: data[i].id, type:0}
                }
              })
              // this.recordList.push({
              //   flag: 'error',
              //   data: {text:data[i].noAnswer}
              // })
            }else{
              this.recordList.push({
                flag: 'AnswerRendering',
                data: {
                  data:{list: data[i].answer, childId: data[i].id,  type:1}
                }
              })
            }
          }
          console.log('this.recordList', this.recordList)
        }else {
          this.recordList = [{
            flag: 'NewConversation',
          }]
        }
      })
    },
    // getActivitiesData(DetailId){
    //     getProcessingProcess(DetailId).then(res=>{
    //       this.dialogueDetailData = res.data
    //       // console.log('getActives_res', this.dialogueDetailData)
    //     })
    // },
    scrollToBottom() {
      this.$nextTick(() => {
        const scrollContainer = this.$refs.dialogContainer;
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
      });
    },
    sendQuestions(event){
      try {
        console.log('this.formattedContent', this.formattedContent)
        const regex = /^[\r\n]*$/;
        if (this.formattedContent !== '' && !regex.test(this.formattedContent) ) {
          console.log('this.bordflag', this.bordflag)
          if(this.bordflag){
            console.log('this.bordflag')
            this.newconversationnew(this.formattedContent)
          }else {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const currentDate = `${year}-${month}-${day} ${hours}:${minutes}`;
            const hasValue = this.recordList.some(item => item.content === currentDate);
            if (!hasValue) {
              this.recordList.push({
                flag: 'dateAndTime',
                content: currentDate
              })
            }
            this.NewConversation = true
            // console.log('this.content', this.content)
            this.propsContent = this.formattedContent
            // this.recordList.push(this.content)
            this.content = ''
            this.formattedContent = ''
            this.recordList.push({
              flag: 'AssistantQuotation',
              content: this.propsContent
            })
            const groupDetailsSaveReqVO = {
              "id": this.id,
              "question": this.propsContent
            }
              console.log('this.recordList',this.recordList)
              console.log('groupDetailsSaveReqVO',groupDetailsSaveReqVO)
            getAnswersByQuestion(groupDetailsSaveReqVO).then(res => {
              // console.log('res', res)
              this.dialogueDetailId = res.data.id
              // this.childId = res.data.id
              if (res.data.answer.length === 0) {
                // this.recordList.push({
                //   flag: 'error',
                //   data: {text:res.data.noAnswer}
                // })
                this.recordList.push({
                  flag: 'AnswerRendering',
                  data: {
                    data:{list:res.data.noAnswer,childId:res.data.id, type:0}
                  },

                })
              }else{
                debugger
                this.recordList.push({
                  flag: 'AnswerRendering',
                  data: {
                    data:{list:res.data.answer,childId:res.data.id,type:1}
                  },
                })
              }
              // this.getActivitiesData(this.dialogueDetailId)
              this.NewConversation = false
              this.formattedContent = ''
            })
          }
        }else{
          this.open4()
        }
      } catch(e) {
        // console.log(e)
      }
    },
    newconversationnew(text){
      const data1 = {groupName:'新建对话' }
      adddialogue(data1).then(res => {
        console.log('对话框页面新建成功了')
        dialoguequery().then(res => {
          const tenantId = res.data.list;
          tenantId[0].text = text
          console.log('tenantId',tenantId,text)
          this.$emit('backhaul',tenantId)
          this.bordflag = false
        });
      });
    },
    updateContent(event) {
      this.content = event.target.innerText; // 获取纯文本内容
      this.observeDivHeight();
    },
    insertImage() {
      // 插入图片的逻辑，这里只是插入一个简单的图片占位符
      const imagePlaceholder = '<img src="@/assets/images/static/send_buttom.png" alt="图片" style="width: 50px; height: 50px;">';
      this.formattedContent += imagePlaceholder + ' '; // 在内容末尾添加图片
      // 注意：这里假设用户不会在图片后面紧接着输入文字，如果需要处理这种情况，逻辑会更复杂
    },
    observeDivHeight() {
      try {
        const targetNode = this.$refs.rich_textarea;
        const config = { attributes: true, childList: true, subtree: true };
        // 当目标节点或其后代节点的属性或子节点列表发生更改时，回调函数将被调用
        this.observer = new MutationObserver((mutationsList, observer) => {
          for(let mutation of mutationsList) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
              this.updateDivHeight();
            } else if (mutation.type === 'childList') {
              this.updateDivHeight();
            }
          }
        });
        // 配置观察器选项:
        this.observer.observe(targetNode, config);
        // 首次获取高度
        this.updateDivHeight();
      } catch (error) {
        // 捕获错误并处理它
        // this.error = `获取数据时发生错误: ${error.message}`;
      }
    },
    updateDivHeight() {
      console.log('高度变化了进来了')
      // console.log('高度变化了', this.isEnter)
      if (this.isEnter !== 'Enter') {
        try {
          this.divHeight = this.$refs.rich_textarea.offsetHeight;
          // console.log('Div height changed:', this.divHeight);
          this.input_box_height = this.divHeight
          console.log('高度变化了', this.input_box_height)
        } catch (error) {
        // 捕获错误并处理它
        // this.error = `获取数据时发生错误: ${error.message}`;
      }
      }
    },
    keyDown(e) { 
       // 回车则执行登录方法 enter键的ASCII是13
      if(e.key === 'Enter') {
        this.isEnter = 'Enter'
        // console.log('输入框监听到使用了enter111', e.srcElement._prevClass)
        // console.log('this.formattedContent', this.formattedContent)
        // this.sendQuestions()
        const chineseRegex = /[\u4e00-\u9fa5]/;  
        // 英文的正则表达式（这里假设包括大小写字母和空格）  
        const englishRegex = /[a-zA-Z\s]/;  
        // 数字的正则表达式  
        const numberRegex = /\d/;  
        debugger
        if (chineseRegex.test(this.formattedContent) ||  numberRegex.test(this.formattedContent)) {
          console.log('进入了正则判断')
          this.sendQuestions()
        }
        this.isEnter = ''
      }
    },
    clearContent(){
      if (this.formattedContent === '请输入你的交易要求' && this.content === '请输入你的交易要求') {
        this.$refs.rich_textarea.innerText = '';
      }
    },
    open4() {
      // if (this.message != '') {
      //   this.message.close()
      // }
      // this.message = this.$message({
      //   showClose: true,
      //   message: '输入内容不得为空',
      //   type: 'error',
      //   // duration: 0
      // });
      const TIME_COUNT = 3;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 0) {
            this.count -= 1;
            this.$forceUpdate()
          } else {
            clearInterval(this.timer);
            // 倒计时结束后执行的操作，例如跳转页面或显示内容
            this.timer = null
          }
          console.log("this.count", this.count);
          const notificationDOM = document.getElementsByClassName('test')
          document.getElementsByClassName('test')[notificationDOM.length-1].innerText = "输入内容不得为空 ("+this.count+"s)" 
          console.log(notificationDOM);
        }, 1000);
        let $notify = this.$notify({
        //   title: 'HTML 片段',
          dangerouslyUseHTMLString: true,
          duration: 3000,
          type: 'error',
          message: <div><div style="float: right;margin-left: 0px;width: 230px;"><span class="test">输入内容不得为空&nbsp;(3s)</span></div></div>
        });
        console.log($notify);
      }
    },
    onPaste(e) {
      // this.observeDivHeight()
      e.preventDefault();
      const text = (e.clipboardData || window.clipboardData).getData('text/plain');
      // 更新数据，但不包含样式
      this.formattedContent += text;
      this.content += this.formattedContent
      this.observeDivHeight()
    },
  },
  destroyed() {
    window.addEventListener("keydown", this.keyDown); // 销毁回车事件
  },
};
</script>

<style lang="scss" scoped>
.dialogue_area{
  // background: -webkit-linear-gradient(top,#85c4fd,#779ce3,#6386db);
  // background-image: linear-gradient(0deg, #F5F9FF 0%, #E9F1FF 99%);
  // width: 70%;
  // width: 1000px;
  text-align: left;
}
.record_section{
  height: 75vh;
  overflow-y: scroll;
  overflow-x: hidden;
}
.dialogue_component{
  margin-left: 5%;
}
.input_body{
  width: 100%;
  text-align: center;
}
.centered-input .el-input__inner {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px; /* 设置你想要的高度 */
}
.input_box{
  border-radius: 10px; /* 设置所有四个边角为10px的圆角 */
  margin: 0 auto;
  max-width: 100%;
  // min-width: 100px;
  width: 100%;
  // max-height: 168px;
  bottom: 40px;
  background: #FFFFFF;
  // border: 1px solid #E8E9EB;
  // box-shadow: 0 1px 0 0 rgba(9,18,33,0.02), 0 1px 1px 0 rgba(9,18,33,0.02), 0 3px 3px 0 rgba(9,18,33,0.01), 0 9px 9px 0 rgba(9,18,33,0.01);
  background-clip: padding-box; /* 背景裁剪到填充区域 */
  // background: linear-gradient(to right, #4DCECB, #2468f2, #2468f2, #E45D45); /* 渐变背景 */
  box-shadow: 0 0 0 3px #ffffff; /* 使用box-shadow模拟边框 */
  /* 添加过渡效果 */
  transition: box-shadow 0.3s ease;
}
.input_border{
  padding: 3px 3px 3px 3px;
  border-radius: 15px; /* 设置所有四个边角为10px的圆角 */
  margin: 0 auto;
  max-width: 89%;
  // min-width: 103px;
  width: 82%;
  // max-height: 168px;
  bottom: 40px;
  background: #FFFFFF;
  border: 1px solid #E8E9EB;
  // box-shadow: 0 1px 0 0 rgba(9,18,33,0.02), 0 1px 1px 0 rgba(9,18,33,0.02), 0 3px 3px 0 rgba(9,18,33,0.01), 0 9px 9px 0 rgba(9,18,33,0.01);
  background-clip: padding-box; /* 背景裁剪到填充区域 */
  background: linear-gradient(to right, #4DCECB, #2468f2, #2468f2, #E45D45); /* 渐变背景 */
  // box-shadow: 0 0 0 3px #ffffff; /* 使用box-shadow模拟边框 */
  box-shadow: linear-gradient(to right, #4DCECB, #2468f2, #2468f2, #E45D45); /* 渐变背景 */ ; /* 使用box-shadow模拟边框 */
  /* 添加过渡效果 */
  transition: box-shadow 0.3s ease;
}
.input_box:hover {
  box-shadow: 0 0 0 1px transparent; /* 透明边框，仅用于占位 */
  outline: 10px solid linear-gradient(to right, #4DCECB, #2468f2, #2468f2, #E45D45); /* 使用outline模拟渐变边框 */
}

.send_button{
  margin-top: -43px;
  margin-left: 10px;
  height: 28px;
  width: 28px;
  background-size: 100%;
  background-image: url('~@/assets/images/static/send_buttom_big.png');
  cursor: default; /* 默认光标样式 */
  transition: cursor 0.3s ease; /* 可选，使光标变化更平滑 */
}
.send_button1{
  margin-top: -43px;
  margin-left: 10px;
  height: 28px;
  width: 28px;
  background-size: 100%;
  background-image: url('~@/assets/images/static/编组 13@2x.png');
  cursor: default; /* 默认光标样式 */
  transition: cursor 0.3s ease; /* 可选，使光标变化更平滑 */
}
.send_button:hover {
  /* 定义div在鼠标悬停时的样式 */
  cursor: pointer; /* 小手光标样式 */
  /* 你可以在这里添加其他悬停时的样式变化，比如背景色变化等 */
  // background-size: 100%;
  // background-image: url('~@/assets/images/static/编组 13@2x.png');
}
// .send_ntype {
//   width: 60px;
//   height: 100%;
// }
// .send_ntype:hover {
//   /* 定义div在鼠标悬停时的样式 */
//   cursor: pointer; /* 小手光标样式 */
//   /* 你可以在这里添加其他悬停时的样式变化，比如背景色变化等 */
//   background-size: 100%;
//   background-image: url('~@/assets/images/static/编组 13@2x.png');
// }
/* CSS */
::-webkit-scrollbar {
    width: 0px; /* 控制滚动条宽度 */
}

::-webkit-scrollbar-track {
    background-color: #f5f5f5; /* 控制滚动条背景色 */
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.rich_textarea {
  font-size: 15px !important;
  width: 106%;
  // border: 1px solid #ccc;
  margin-top: 8px;
  padding: 10px;
  color: #151B26;
 font-size: 15px !important;
  width: 106%;
  // border: 1px solid #ccc;
  margin-top: 8px;
  padding: 10px;
  color: #84868C;
  margin-left: -16px;
  position: relative;
  max-height: 100px;
  overflow-y: auto; /* 超出最大高度时出现滚动条 */
  background-color: #FFFFFF;
}
.image-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
</style>
<style  lang="scss">
.el-message {
  min-width: 257px;
  padding: 5px 3px 5px 7px;
}
.el-textarea__inner {
  display: block;
  resize: initial;
  padding: 20px 15px;
  line-height: 1.5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 108%;
  max-height: 80px;
  min-height: 60px !important;
  margin-left: -23px;
  font-size: inherit;
  color: #151B26;
  background-color: #ffffff00;
  background-image: none;
  border: 1px solid #dcdfe600;
  border-radius: 4px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.el-textarea__inner:hover {
  border-color: #C0C4CC00;
}
.el-textarea__inner:focus {
  outline: none;
  border-color: #1890ff00;
}
*::-webkit-scrollbar {
  display: none;
}
</style>
